package volatile1;

import lombok.SneakyThrows;
import org.junit.jupiter.api.Test;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author ZhuQi
 * @ClassName Demo2
 * @Date 2022/9/14 17:23
 * @Version 1.0
 * @Description 测试 lock 会刷新线程工作空间的变量缓存
 */
public class Demo2 {

    public static boolean flag = true;

    /**
     * 测试结果:加锁会导致重新 read 主内存中的值，再 load 到自己的工作内存
     * @param args
     */
    @SneakyThrows
    public static void main(String[] args) {
        new Thread(()->{
            System.out.println(Thread.currentThread().getName() + " -- coming");
            while (flag) {
                synchronized (Demo2.class){

                }
            }
            System.out.println(Thread.currentThread().getName() + " -- out -- flag:" + flag);
        }).start();

        TimeUnit.SECONDS.sleep(1);
        flag = false;
        System.out.println(Thread.currentThread().getName() + " -- flag:" + flag);
    }


    /**
     * 测试内容: ReentrantLock 加锁 会不会刷新 工作内存的变量
     * 测试结果: 结果同 synchronized
     */
    @Test
    public void test() throws Exception {
        ReentrantLock lock = new ReentrantLock();
        new Thread(()->{
            System.out.println(Thread.currentThread().getName() + " -- coming");
            while (flag) {
                lock.lock();
                lock.unlock();
            }
            System.out.println(Thread.currentThread().getName() + " -- out -- flag:" + flag);
        }).start();

        TimeUnit.SECONDS.sleep(1);
        flag = false;
        System.out.println(Thread.currentThread().getName() + " -- flag:" + flag);
    }

}
